<!DOCTYPE HTML>
<html lang="en" class="sidebar-visible no-js">
    <head>
        <!-- Book generated using mdBook -->
        <meta charset="UTF-8">
        <title>Hello wasm-pack!</title>
        <meta content="text/html; charset=utf-8" http-equiv="Content-Type">
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="theme-color" content="#ffffff" />

        <link rel="shortcut icon" href="favicon.png">
        <link rel="stylesheet" href="css/variables.css">
        <link rel="stylesheet" href="css/general.css">
        <link rel="stylesheet" href="css/chrome.css">
        <link rel="stylesheet" href="css/print.css" media="print">

        <!-- Fonts -->
        <link rel="stylesheet" href="FontAwesome/css/font-awesome.css">
        <link href="https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800" rel="stylesheet" type="text/css">
        <link href="https://fonts.googleapis.com/css?family=Source+Code+Pro:500" rel="stylesheet" type="text/css">

        <!-- Highlight.js Stylesheets -->
        <link rel="stylesheet" href="highlight.css">
        <link rel="stylesheet" href="tomorrow-night.css">
        <link rel="stylesheet" href="ayu-highlight.css">

        <!-- Custom theme stylesheets -->
        

        
    </head>
    <body class="light">
        <!-- Provide site root to javascript -->
        <script type="text/javascript">
            var path_to_root = "";
            var default_theme = "light";
        </script>

        <!-- Work around some values being stored in localStorage wrapped in quotes -->
        <script type="text/javascript">
            try {
                var theme = localStorage.getItem('mdbook-theme');
                var sidebar = localStorage.getItem('mdbook-sidebar');

                if (theme.startsWith('"') && theme.endsWith('"')) {
                    localStorage.setItem('mdbook-theme', theme.slice(1, theme.length - 1));
                }

                if (sidebar.startsWith('"') && sidebar.endsWith('"')) {
                    localStorage.setItem('mdbook-sidebar', sidebar.slice(1, sidebar.length - 1));
                }
            } catch (e) { }
        </script>

        <!-- Set the theme before any content is loaded, prevents flash -->
        <script type="text/javascript">
            var theme;
            try { theme = localStorage.getItem('mdbook-theme'); } catch(e) { } 
            if (theme === null || theme === undefined) { theme = default_theme; }
            document.body.className = theme;
            document.querySelector('html').className = theme + ' js';
        </script>

        <!-- Hide / unhide sidebar before it is displayed -->
        <script type="text/javascript">
            var html = document.querySelector('html');
            var sidebar = 'hidden';
            if (document.body.clientWidth >= 1080) {
                try { sidebar = localStorage.getItem('mdbook-sidebar'); } catch(e) { }
                sidebar = sidebar || 'visible';
            }
            html.classList.remove('sidebar-visible');
            html.classList.add("sidebar-" + sidebar);
        </script>

        <nav id="sidebar" class="sidebar" aria-label="Table of contents">
            <ol class="chapter"><li><a href="introduction.html"><strong aria-hidden="true">1.</strong> Introduction</a></li><li><a href="quickstart.html"><strong aria-hidden="true">2.</strong> Quickstart</a></li><li><a href="prerequisites/index.html"><strong aria-hidden="true">3.</strong> Prerequisites</a></li><li><ol class="section"><li><a href="prerequisites/npm.html"><strong aria-hidden="true">3.1.</strong> npm (optional)</a></li><li><a href="prerequisites/considerations.html"><strong aria-hidden="true">3.2.</strong> considerations</a></li><li><a href="prerequisites/non-rustup-setups.html"><strong aria-hidden="true">3.3.</strong> Non-rustup setups</a></li></ol></li><li><a href="commands/index.html"><strong aria-hidden="true">4.</strong> Commands</a></li><li><ol class="section"><li><a href="commands/new.html"><strong aria-hidden="true">4.1.</strong> new</a></li><li><a href="commands/build.html"><strong aria-hidden="true">4.2.</strong> build</a></li><li><a href="commands/test.html"><strong aria-hidden="true">4.3.</strong> test</a></li><li><a href="commands/pack-and-publish.html"><strong aria-hidden="true">4.4.</strong> pack and publish</a></li><li><a href="commands/init.html"><strong aria-hidden="true">4.5.</strong> init (DEPRECATED)</a></li></ol></li><li><a href="tutorials/index.html"><strong aria-hidden="true">5.</strong> Tutorials</a></li><li><ol class="section"><li><a href="tutorials/hybrid-applications-with-webpack/index.html"><strong aria-hidden="true">5.1.</strong> Hybrid applications with Webpack</a></li><li><ol class="section"><li><a href="tutorials/hybrid-applications-with-webpack/getting-started.html"><strong aria-hidden="true">5.1.1.</strong> Getting started</a></li><li><a href="tutorials/hybrid-applications-with-webpack/using-your-library.html"><strong aria-hidden="true">5.1.2.</strong> Using your library</a></li></ol></li><li><a href="tutorials/npm-browser-packages/index.html"><strong aria-hidden="true">5.2.</strong> npm browser packages</a></li><li><ol class="section"><li><a href="tutorials/npm-browser-packages/getting-started.html"><strong aria-hidden="true">5.2.1.</strong> Getting started</a></li><li><ol class="section"><li><a href="tutorials/npm-browser-packages/getting-started/manual-setup.html"><strong aria-hidden="true">5.2.1.1.</strong> Manual Setup</a></li></ol></li><li><a href="tutorials/npm-browser-packages/template-deep-dive/index.html"><strong aria-hidden="true">5.2.2.</strong> Template deep dive</a></li><li><ol class="section"><li><a href="tutorials/npm-browser-packages/template-deep-dive/cargo-toml.html"><strong aria-hidden="true">5.2.2.1.</strong> Cargo.toml</a></li><li><a href="tutorials/npm-browser-packages/template-deep-dive/src-lib-rs.html"><strong aria-hidden="true">5.2.2.2.</strong> src/lib.rs</a></li><li><a href="tutorials/npm-browser-packages/template-deep-dive/src-utils-rs.html"><strong aria-hidden="true">5.2.2.3.</strong> src/utils.rs</a></li><li><a href="tutorials/npm-browser-packages/template-deep-dive/wee_alloc.html"><strong aria-hidden="true">5.2.2.4.</strong> wee_alloc</a></li><li><a href="tutorials/npm-browser-packages/template-deep-dive/tests-web-rs.html"><strong aria-hidden="true">5.2.2.5.</strong> tests/web.rs</a></li></ol></li><li><a href="tutorials/npm-browser-packages/building-your-project.html"><strong aria-hidden="true">5.2.3.</strong> Building your project</a></li><li><a href="tutorials/npm-browser-packages/testing-your-project.html"><strong aria-hidden="true">5.2.4.</strong> Testing your project</a></li><li><a href="tutorials/npm-browser-packages/packaging-and-publishing.html"><strong aria-hidden="true">5.2.5.</strong> Packaging and publishing</a></li><li><a href="tutorials/npm-browser-packages/using-your-library.html"><strong aria-hidden="true">5.2.6.</strong> Using your library</a></li></ol></li></ol></li><li><a href="cargo-toml-configuration.html"><strong aria-hidden="true">6.</strong> Cargo.toml Configuration</a></li><li><a href="contributing.html"><strong aria-hidden="true">7.</strong> Contributing</a></li></ol>
        </nav>

        <div id="page-wrapper" class="page-wrapper">

            <div class="page">
                <style>
  header.warning {
    background-color: rgb(242, 222, 222);
    border-bottom-color: rgb(238, 211, 215);
    border-bottom-left-radius: 4px;
    border-bottom-right-radius: 4px;
    border-bottom-style: solid;
    border-bottom-width: 0.666667px;
    border-image-outset: 0 0 0 0;
    border-image-repeat: stretch stretch;
    border-image-slice: 100% 100% 100% 100%;
    border-image-source: none;
    border-image-width: 1 1 1 1;
    border-left-color: rgb(238, 211, 215);
    border-left-style: solid;
    border-left-width: 0.666667px;
    border-right-color: rgb(238, 211, 215);
    border-right-style: solid;
    border-right-width: 0.666667px;
    border-top-color: rgb(238, 211, 215);
    border-top-left-radius: 4px;
    border-top-right-radius: 4px;
    border-top-style: solid;
    border-top-width: 0.666667px;
    color: rgb(185, 74, 72);
    margin-bottom: 0px;
    margin-left: 0px;
    margin-right: 0px;
    margin-top: 30px;
    padding-bottom: 8px;
    padding-left: 14px;
    padding-right: 35px;
    padding-top: 8px;
    text-align: center;
  }
</style>
<header class='warning'>
  This documentation is
  <a
  href="https://blog.rust-lang.org/inside-rust/2025/07/21/sunsetting-the-rustwasm-github-org/">no
  longer maintained at this domain</a>, and is now maintained
  <a href="https://drager.github.io/wasm-pack/">
  at drager.github.io/wasm-pack</a> instead.
</header>

                <div id="menu-bar" class="menu-bar">
                    <div id="menu-bar-sticky-container">
                        <div class="left-buttons">
                            <button id="sidebar-toggle" class="icon-button" type="button" title="Toggle Table of Contents" aria-label="Toggle Table of Contents" aria-controls="sidebar">
                                <i class="fa fa-bars"></i>
                            </button>
                            <button id="theme-toggle" class="icon-button" type="button" title="Change theme" aria-label="Change theme" aria-haspopup="true" aria-expanded="false" aria-controls="theme-list">
                                <i class="fa fa-paint-brush"></i>
                            </button>
                            <ul id="theme-list" class="theme-popup" aria-label="Themes" role="menu">
                                <li role="none"><button role="menuitem" class="theme" id="light">Light (default)</button></li>
                                <li role="none"><button role="menuitem" class="theme" id="rust">Rust</button></li>
                                <li role="none"><button role="menuitem" class="theme" id="coal">Coal</button></li>
                                <li role="none"><button role="menuitem" class="theme" id="navy">Navy</button></li>
                                <li role="none"><button role="menuitem" class="theme" id="ayu">Ayu</button></li>
                            </ul>
                            
                        </div>

                        <h1 class="menu-title">Hello wasm-pack!</h1> 

                        <div class="right-buttons">
                            <a href="print.html" title="Print this book" aria-label="Print this book">
                                <i id="print-button" class="fa fa-print"></i>
                            </a>
                            
                        </div>
                    </div>
                </div>

                

                <!-- Apply ARIA attributes after the sidebar and the sidebar toggle button are added to the DOM -->
                <script type="text/javascript">
                    document.getElementById('sidebar-toggle').setAttribute('aria-expanded', sidebar === 'visible');
                    document.getElementById('sidebar').setAttribute('aria-hidden', sidebar !== 'visible');
                    Array.from(document.querySelectorAll('#sidebar a')).forEach(function(link) {
                        link.setAttribute('tabIndex', sidebar === 'visible' ? 0 : -1);
                    });
                </script>

                <div id="content" class="content">
                    <main>
                        <p><img src="https://rustwasm.github.io/wasm-pack/public/img/wasm-ferris.png" alt="wasm ferris" /></p>
<h1 style="text-align: center;">Welcome to the <code>wasm-pack</code> docs!</h1>
<p>This tool seeks to be a one-stop shop for building and working with rust-
generated WebAssembly that you would like to interop with JavaScript, in the
browser or with Node.js. <code>wasm-pack</code> helps you build rust-generated
WebAssembly packages that you could publish to the npm registry, or otherwise use
alongside any javascript packages in workflows that you already use, such as <a href="https://webpack.js.org/">webpack</a>.</p>
<p>This project is a part of the <a href="https://github.com/rustwasm/team">rust-wasm</a> group. You can find more info by
visiting that repo!</p>
<p><img src="https://github.com/rustwasm/wasm-pack/raw/master/demo.gif" alt="demo" /></p>
<a class="header" href="#quickstart" id="quickstart"><h1>Quickstart</h1></a>
<ol>
<li>Install <code>rust</code> using <a href="https://rustup.rs/"><code>rustup</code></a>.</li>
<li><a href="https://rustwasm.github.io/wasm-pack/installer/">Install this tool.</a></li>
<li>Run <code>wasm-pack new hello-wasm</code>.</li>
<li><code>cd hello-wasm</code></li>
<li>Run <code>wasm-pack build --target web</code>.</li>
<li>This tool generates files in a <code>pkg</code> dir</li>
<li>Import it: <code>import init, { greet } from &quot;./pkg/hello_wasm.js&quot;</code>, initialize it: <code>await init()</code>, and then use it: <code>greet()</code></li>
<li>To publish to npm, run <code>wasm-pack publish</code>. You may need to login to the
registry you want to publish to. You can login using <code>wasm-pack login</code>.</li>
</ol>
<a class="header" href="#prerequisites" id="prerequisites"><h1>Prerequisites</h1></a>
<p>First you'll want to <a href="https://rustwasm.github.io/wasm-pack/installer/">install the <code>wasm-pack</code> CLI</a>, and <code>wasm-pack -V</code> should print the version that you just installed.</p>
<p>Next, since <code>wasm-pack</code> is a build tool, you'll want to make sure you have
<a href="https://www.rust-lang.org/tools/install">Rust</a> installed. Make sure <code>rustc -V</code> prints out at least 1.30.0.</p>
<p>Finally, if you're using <code>wasm-pack</code> to publish to NPM, you'll want
to <a href="./npm.html">install and configure <code>npm</code></a>. In the future, we intend to rewrite the
npm registry client bits so that the need for a Node runtime is eliminated. If
you're excited about that work- you should reach out to the maintainers and get
involved!</p>
<p>Using a non-rustup setup? Learn how to configure it for wasm-pack <a href="./non-rustup-setups.html">here</a>.</p>
<a class="header" href="#npm" id="npm"><h1>npm</h1></a>
<p>Currently, <code>wasm-pack</code> requires that you have npm installed to pack and publish your
package. Longterm, this will be replaced by a Rust only version.</p>
<p>If you would rather use another package manager that interfaces with the npm registry
you may, however, the <code>pack</code>, <code>publish</code>, and <code>login</code> commands wrap the npm CLI interface
and as a result require that npm be installed.</p>
<p>You can install <a href="https://www.npmjs.com">npm</a> by following <a href="https://docs.npmjs.com/downloading-and-installing-node-js-and-npm">these instructions</a>.</p>
<a class="header" href="#npm-account" id="npm-account"><h3>npm Account</h3></a>
<p>Part of the <code>wasm-pack</code> workflow is to publish your package to the npm Registry.</p>
<p>Regardless of which package manager CLI tool you prefer, if you wish to publish
your package to the npm registry you'll need an npm account.</p>
<p>You can find information about signing up for npm <a href="https://www.npmjs.com/signup">here</a>.</p>
<a class="header" href="#nodejs" id="nodejs"><h1>nodejs</h1></a>
<p>Currently, <code>wasm-pack</code> generated npm modules require us to you have <a href="https://github.com/node-fetch/node-fetch">fetch</a> polyfill in your node project.</p>
<p>If there is a module from <code>wasm-pack build --target nodejs</code> you may encounter some errors regarding global <code>Headers</code>, <code>Request</code>, <code>Response</code> and <code>fetch</code> Web APIs.</p>
<a class="header" href="#common-errors" id="common-errors"><h2>Common errors:</h2></a>
<pre><code class="language-js">ReqwestError(reqwest::Error { kind: Builder, source: &quot;JsValue(ReferenceError: Headers is not defined
ReqwestError(reqwest::Error { kind: Builder, source: &quot;JsValue(ReferenceError: Request is not defined

    var ret = getObject(arg0) instanceof Response;
ReferenceError: Response is not defined
</code></pre>
<a class="header" href="#workaround" id="workaround"><h2>Workaround</h2></a>
<p>Import or declare fetch and objects: Headers, Request, Response</p>
<pre><code class="language-ts">// CommonJS
const fetch = require('node-fetch');

// ES Module
import fetch from 'node-fetch';

// @ts-ignore
global.fetch = fetch;
// @ts-ignore
global.Headers = fetch.Headers;
// @ts-ignore
global.Request = fetch.Request;
// @ts-ignore
global.Response = fetch.Response;
</code></pre>
<a class="header" href="#non-rustup-setups" id="non-rustup-setups"><h1>Non-Rustup setups</h1></a>
<p><code>wasm-pack</code> compiles your code using the <code>wasm32-unknown-unknown</code> target. <code>wasm-pack</code> will automatically add this target for Rustup setups if you don't already have it installed by doing <code>rustup target add wasm32-unknown-unknown</code>. However, if you're not using Rustup, then we won't be able to do this automatically, and you'll have to do this yourself.</p>
<a class="header" href="#manually-add-wasm32-unknown-unknown" id="manually-add-wasm32-unknown-unknown"><h2>Manually add wasm32-unknown-unknown</h2></a>
<p><em>Disclaimer: This is not guaranteed to work for every setup. These instructions below are specific for setups that match the exact rustc release, which means that the downloaded wasm32 target can be incompatible.</em></p>
<p>To manually add the <code>wasm32-unknown-unknown</code> target you will need to download it from the rust-lang website and put the contents in the correct folder.</p>
<p>All the targets for all the different <code>rustc</code> versions are not presented in a human way on a website (yet) for you to just select the one you want and download it, one reason for this is that Rustup handles all of this for you and the packaging of targets was mainly built for tools. However, the following steps will walk through how to do this.</p>
<p>First, check what version of <code>rustc</code> you're using by running <code>rustc --version</code>. This should display something like: <code>rustc 1.33.0 (2aa4c46cf 2019-02-28)</code>. Then you need to download the correct wasm32 target for your rustc version. The rustc version is part of the url, which means for <code>rustc 1.33.0</code> the url will look like this: <code>https://static.rust-lang.org/dist/rust-std-1.33.0-wasm32-unknown-unknown.tar.gz</code>.</p>
<p>Here's some examples of urls for different rustc versions:</p>
<ul>
<li>Nightly https://static.rust-lang.org/dist/rust-std-nightly-wasm32-unknown-unknown.tar.gz</li>
<li>Specific date nightly (2019-03-10) https://static.rust-lang.org/dist/2019-03-10/rust-std-nightly-wasm32-unknown-unknown.tar.gz</li>
<li>Beta https://static.rust-lang.org/dist/rust-std-beta-wasm32-unknown-unknown.tar.gz</li>
</ul>
<p>You should be able to download this either by doing <code>wget https://static.rust-lang.org/dist/rust-std-1.33.0-wasm32-unknown-unknown.tar.gz</code> or by just visiting the url in a web browser.</p>
<p>After you have downloaded this tarball at a location of your choice, you should unpack it. This should result in a folder named <code>rust-std-1.33.0-wasm32-unknown-unknown</code> that contains some folders and files, but the interesting one is a folder called <code>rust-std-wasm32-unknown-unknown</code> which contains a <code>lib</code> and that should contain a <code>rustlib</code> folder and in that, a folder called <code>wasm32-unknown-unknown</code>. This is the folder we want to move.</p>
<p>Here's how the structure should look like for rustc 1.33.0:</p>
<pre><code>rust-std-1.33.0-wasm32-unknown-unknown
├── components
├── install.sh
├── rust-installer-version
└── rust-std-wasm32-unknown-unknown
    ├── lib
    │   └── rustlib
    │       └── wasm32-unknown-unknown
</code></pre>
<p>To know where we should move this <code>wasm32-unknown-unknown</code> folder we need to run <code>rustc --print sysroot</code> which should print a path that looks something like this (this will vary on different operating systems): <code>/home/user/rust/rust-1.33.0-2019-02-28-2aa4c46cf</code>. That folder should contain a <code>lib</code> folder that contains a <code>rustlib</code> folder. We should move the <code>wasm32-unknown-unknown</code> to this folder.</p>
<p>On unix-like operating systems we can do that with the following command:
<code>mv rust-std-1.33.0-wasm32-unknown-unknown/rust-std-wasm32-unknown-unknown/lib/rustlib/wasm32-unknown-unknown /home/user/rust/rust-1.33.0-2019-02-28-2aa4c46cf/lib/rustlib/</code> and that should be it!</p>
<a class="header" href="#commands" id="commands"><h1>Commands</h1></a>
<p><code>wasm-pack</code> has several commands to help you during the process of building
a Rust-generated WebAssembly project.</p>
<ul>
<li><code>new</code>: This command generates a new project for you using a template. <a href="./new.html">Learn more</a></li>
<li><code>build</code>: This command builds a <code>pkg</code> directory for you with compiled wasm and generated JS. <a href="./build.html">Learn more</a></li>
<li><code>pack</code> and <code>publish</code>: These commands will create a tarball, and optionally publish it to a registry, such as npm. <a href="./pack-and-publish.html">Learn more</a></li>
</ul>
<a class="header" href="#deprecated-commands" id="deprecated-commands"><h3>Deprecated Commands</h3></a>
<ul>
<li><code>init</code>: This command has been deprecated in favor of <code>build</code>.</li>
</ul>
<a class="header" href="#log-levels" id="log-levels"><h3>Log levels</h3></a>
<p>By default <code>wasm-pack</code> displays a lot of useful information.</p>
<p>You can cause it to display even <em>more</em> information by using <code>--verbose</code>, or you can silence <em>all</em> stdout by using <code>--quiet</code>.</p>
<p>You can also use <code>--log-level</code> to have fine-grained control over wasm-pack's log output:</p>
<ul>
<li><code>--log-level info</code> is the default, it causes all messages to be logged.</li>
<li><code>--log-level warn</code> causes warnings and errors to be displayed, but not info.</li>
<li><code>--log-level error</code> causes only errors to be displayed.</li>
</ul>
<p>These flags are global flags, so they can be used with every command, and they must come <em>before</em> the command:</p>
<pre><code class="language-sh">wasm-pack --log-level error build
wasm-pack --quiet build
wasm-pack --verbose build
</code></pre>
<a class="header" href="#wasm-pack-new" id="wasm-pack-new"><h1>wasm-pack new</h1></a>
<p>The <code>wasm-pack new</code> command creates a new RustWasm project for you,
using <a href="https://github.com/ashleygwilliams/cargo-generate"><code>cargo-generate</code></a> under the hood.</p>
<p>It takes 3 parameters, name, template, and mode:</p>
<pre><code>wasm-pack new &lt;name&gt; --template &lt;template&gt; --mode &lt;normal|noinstall|force&gt;
</code></pre>
<p>The default template is <a href="https://github.com/rustwasm/wasm-pack-template"><code>rustwasm/wasm-pack-template</code></a>.</p>
<a class="header" href="#name" id="name"><h2>Name</h2></a>
<p>The <code>wasm-pack new</code> command must be given a name argument, e.g.:</p>
<pre><code>wasm-pack new myproject
</code></pre>
<a class="header" href="#template" id="template"><h2>Template</h2></a>
<p>The <code>wasm-pack new</code> command can be given an optional template argument, e.g.:</p>
<pre><code>wasm-pack new myproject --template https://github.com/rustwasm/wasm-pack-template
</code></pre>
<p>The template can be an address to a git repo that contains a <a href="https://github.com/ashleygwilliams/cargo-generate"><code>cargo-generate</code></a>
template.</p>
<a class="header" href="#mode" id="mode"><h2>Mode</h2></a>
<p>The <code>wasm-pack new</code> command can be given an optional mode argument, e.g.:</p>
<pre><code>wasm-pack new myproject --mode noinstall
</code></pre>
<p>The mode passed can be either &quot;normal&quot;, &quot;noinstall&quot;, or &quot;force&quot;. &quot;normal&quot; is passed by
default.</p>
<p><code>noinstall</code> means that wasm-pack should not attempt to install any underlying tools.
If a necessary tool cannot be found, the command will error.</p>
<p><code>force</code> means that wasm-pack should not check the local Rust version. If a local Rust
is an unacceptable Rust version, the command will error.</p>
<a class="header" href="#wasm-pack-build" id="wasm-pack-build"><h1>wasm-pack build</h1></a>
<p>The <code>wasm-pack build</code> command creates the files necessary for JavaScript
interoperability and for publishing a package to npm. This involves compiling
your code to wasm and generating a pkg folder. This pkg folder will contain the
wasm binary, a JS wrapper file, your <code>README</code>, and a <code>package.json</code> file.</p>
<p>The <code>pkg</code> directory is automatically <code>.gitignore</code>d by default, since it contains
build artifacts which are not intended to be checked into version
control.<sup><a href="#footnote-0">0</a></sup></p>
<a class="header" href="#path" id="path"><h2>Path</h2></a>
<p>The <code>wasm-pack build</code> command can be given an optional path argument, e.g.:</p>
<pre><code>wasm-pack build examples/js-hello-world
</code></pre>
<p>This path should point to a directory that contains a <code>Cargo.toml</code> file. If no
path is given, the <code>build</code> command will run in the current directory.</p>
<a class="header" href="#output-directory" id="output-directory"><h2>Output Directory</h2></a>
<p>By default, <code>wasm-pack</code> will generate a directory for its build output called <code>pkg</code>.
If you'd like to customize this you can use the <code>--out-dir</code> flag.</p>
<pre><code>wasm-pack build --out-dir out
</code></pre>
<p>The above command will put your build artifacts in a directory called <code>out</code>, instead
of the default <code>pkg</code>.</p>
<a class="header" href="#generated-file-names" id="generated-file-names"><h2>Generated file names</h2></a>
<p>Flag <code>--out-name</code> sets the prefix for output file names. If not provided, package name is used instead.</p>
<p>Usage examples, assuming our crate is named <code>dom</code>:</p>
<pre><code>wasm-pack build
# will produce files
# dom.d.ts  dom.js  dom_bg.d.ts  dom_bg.wasm  package.json  README.md

wasm-pack build --out-name index
# will produce files
# index.d.ts  index.js  index_bg.d.ts  index_bg.wasm  package.json  README.md
</code></pre>
<a class="header" href="#profile" id="profile"><h2>Profile</h2></a>
<p>The <code>build</code> command accepts an optional profile argument: one of <code>--dev</code>,
<code>--profiling</code>, or <code>--release</code>. If none is supplied, then <code>--release</code> is used.</p>
<p>This controls whether debug assertions are enabled, debug info is generated, and
which (if any) optimizations are enabled.</p>
<table><thead><tr><th> Profile       </th><th> Debug Assertions </th><th> Debug Info </th><th> Optimizations </th><th> Notes                                 </th></tr></thead><tbody>
<tr><td> <code>--dev</code>       </td><td> Yes              </td><td> Yes        </td><td> No            </td><td> Useful for development and debugging. </td></tr>
<tr><td> <code>--profiling</code> </td><td> No               </td><td> Yes        </td><td> Yes           </td><td> Useful when profiling and investigating performance issues. </td></tr>
<tr><td> <code>--release</code>   </td><td> No               </td><td> No         </td><td> Yes           </td><td> Useful for shipping to production.    </td></tr>
</tbody></table>
<p>The <code>--dev</code> profile will build the output package using cargo's <a href="https://doc.rust-lang.org/cargo/reference/manifest.html#the-profile-sections">default
non-release profile</a>. Building this way is
faster but applies few optimizations to the output, and enables debug assertions
and other runtime correctness checks. The <code>--profiling</code> and <code>--release</code> profiles
use cargo's release profile, but the former enables debug info as well, which
helps when investigating performance issues in a profiler.</p>
<p>The exact meaning of the profile flags may evolve as the platform matures.</p>
<a class="header" href="#target" id="target"><h2>Target</h2></a>
<p>The <code>build</code> command accepts a <code>--target</code> argument. This will customize the JS
that is emitted and how the WebAssembly files are instantiated and loaded. For
more documentation on the various strategies here, see the <a href="https://rustwasm.github.io/docs/wasm-bindgen/reference/deployment.html">documentation on
using the compiled output</a>.</p>
<pre><code>wasm-pack build --target nodejs
</code></pre>
<table><thead><tr><th> Option    </th><th> Usage </th><th> Description                                                                                                     </th></tr></thead><tbody>
<tr><td> <em>not specified</em> or <code>bundler</code> </td><td> <a href="https://rustwasm.github.io/docs/wasm-bindgen/reference/deployment.html#bundlers">Bundler</a> </td><td> Outputs JS that is suitable for interoperation with a Bundler like Webpack. You'll <code>import</code> the JS and the <code>module</code> key is specified in <code>package.json</code>. <code>sideEffects: false</code> is by default. </td></tr>
<tr><td> <code>nodejs</code>  </td><td> <a href="https://rustwasm.github.io/docs/wasm-bindgen/reference/deployment.html#nodejs">Node.js</a> </td><td> Outputs JS that uses CommonJS modules, for use with a <code>require</code> statement. <code>main</code> key in <code>package.json</code>. </td></tr>
<tr><td> <code>web</code> </td><td> <a href="https://rustwasm.github.io/docs/wasm-bindgen/reference/deployment.html#without-a-bundler">Native in browser</a> </td><td> Outputs JS that can be natively imported as an ES module in a browser, but the WebAssembly must be manually instantiated and loaded. </td></tr>
<tr><td> <code>no-modules</code> </td><td> <a href="https://rustwasm.github.io/docs/wasm-bindgen/reference/deployment.html#without-a-bundler">Native in browser</a> </td><td> Same as <code>web</code>, except the JS is included on a page and modifies global state, and doesn't support as many <code>wasm-bindgen</code> features as <code>web</code> </td></tr>
<tr><td> <code>deno</code> </td><td> <a href="https://rustwasm.github.io/docs/wasm-bindgen/reference/deployment.html#deno">Deno</a> </td><td> Outputs JS that can be natively imported as an ES module in deno. </td></tr>
</tbody></table>
<a class="header" href="#scope" id="scope"><h2>Scope</h2></a>
<p>The <code>build</code> command also accepts an optional <code>--scope</code> argument. This will scope
your package name, which is useful if your package name might conflict with
something in the public registry. For example:</p>
<pre><code>wasm-pack build examples/js-hello-world --scope test
</code></pre>
<p>This command would create a <code>package.json</code> file for a package called
<code>@test/js-hello-world</code>. For more information about scoping, you can refer to
the npm documentation <a href="https://docs.npmjs.com/misc/scope">here</a>.</p>
<a class="header" href="#mode-1" id="mode-1"><h2>Mode</h2></a>
<p>The <code>build</code> command accepts an optional <code>--mode</code> argument.</p>
<pre><code>wasm-pack build examples/js-hello-world --mode no-install
</code></pre>
<table><thead><tr><th> Option        </th><th> Description                                                                              </th></tr></thead><tbody>
<tr><td> <code>no-install</code>  </td><td> <code>wasm-pack build</code> implicitly and create wasm binding without installing <code>wasm-bindgen</code>.  </td></tr>
<tr><td> <code>normal</code>      </td><td> do all the stuffs of <code>no-install</code> with installed <code>wasm-bindgen</code>.                         </td></tr>
</tbody></table>
<a class="header" href="#extra-options" id="extra-options"><h2>Extra options</h2></a>
<p>The <code>build</code> command can pass extra options straight to <code>cargo build</code> even if
they are not supported in wasm-pack. To use them simply add the extra arguments
at the very end of your command, just as you would for <code>cargo build</code>. For
example, to build the previous example using cargo's offline feature:</p>
<pre><code>wasm-pack build examples/js-hello-world --mode no-install -- --offline
</code></pre>
<hr style="font-size: 1.5em; margin-top: 2.5em"/>
<p><sup id="footnote-0">0</sup> If you need to include additional assets in the pkg
directory and your NPM package, we intend to have a solution for your use case
soon. <a href="#wasm-pack-build">↩</a></p>
<a class="header" href="#wasm-pack-test" id="wasm-pack-test"><h1>wasm-pack test</h1></a>
<p>The <code>wasm-pack test</code> command wraps the <a href="https://rustwasm.github.io/wasm-bindgen/wasm-bindgen-test/index.html">wasm-bindgen-test-runner</a>
CLI allowing you to run wasm tests in different browsers without needing to install the different
webdrivers yourself.</p>
<pre><code>wasm-pack test --help
</code></pre>
<a class="header" href="#path-1" id="path-1"><h2>Path</h2></a>
<p>The <code>wasm-pack test</code> command can be given an optional path argument.</p>
<p>This path should point to a directory that contains a <code>Cargo.toml</code> file. If no
path is given, the <code>test</code> command will run in the current directory.</p>
<pre><code># Run tests for the current directory's crate
wasm-pack test

# Run tests for a specified crate
wasm-pack test crates/crate-in-my-workspace
</code></pre>
<a class="header" href="#profile-1" id="profile-1"><h2>Profile</h2></a>
<p>The <code>test</code> command accepts an optional profile argument: <code>--release</code>.</p>
<p>If none is supplied, then a debug test build will be used.</p>
<a class="header" href="#test-environment" id="test-environment"><h2>Test environment</h2></a>
<p>Choose where to run your tests by passing in any combination of testing environment flags.</p>
<p><code>--headless</code> is useful for running browser tests in a headless browser as part of a CI process.</p>
<pre><code>wasm-pack test --node --firefox --chrome --safari --headless
</code></pre>
<a class="header" href="#extra-options-1" id="extra-options-1"><h2>Extra options</h2></a>
<p>The <code>test</code> command can pass extra options straight to <code>cargo test</code> even if they are not
supported in wasm-pack.</p>
<p>To use them simply add the extra arguments at the very end of your command, just
as you would for <code>cargo test</code>.</p>
<p><code>cargo test -h</code> for a list of all options that you can pass through.</p>
<a class="header" href="#running-only-some-tests" id="running-only-some-tests"><h2>Running only some tests</h2></a>
<p>When debugging a specific issue, you may find yourself wanting to run a subset of tests, instead of your entire suite of tests.</p>
<p>Here are a few examples of how to run a subset of your tests:</p>
<pre><code># Example directory structure
$ tree crates/foo
├── Cargo.toml
├── README.md
├── src
│   ├── diff
│   │   ├── diff_test_case.rs
│   │   └── mod.rs
│   ├── lib.rs
└── tests
    ├── diff_patch.rs
    └── node.rs
</code></pre>
<pre><code># Run all tests in tests/diff_patch.rs in Firefox
wasm-pack test crates/foo --firefox --headless --test diff_patch

# Run all tests in tests/diff_patch.rs that contain the word &quot;replace&quot;
wasm-pack test crates/foo --firefox --headless --test diff_patch replace

# Run all tests inside of a `tests` module inside of src/lib/diff.rs
wasm-pack test crates/foo --firefox --headless --lib diff::tests

# Same as the above, but only if they contain the word replace
wasm-pack test crates/foo --firefox --headless --lib diff::tests::replace
</code></pre>
<p>Note that you can also filter tests by location in which they're supposed to
run. For example:</p>
<pre><code># Run all tests which are intended to execute in Node.js
wasm-pack test --node

# Run all tests which are intended to be executed in a browser
wasm-pack test --firefox --headless
</code></pre>
<a class="header" href="#pack-and-publish" id="pack-and-publish"><h1>pack and publish</h1></a>
<p>The <code>publish</code> and <code>pack</code> commands interact with the pkg directory that's
created when you run <code>wasm-pack build</code>. The <code>pack</code> command creates a tarball
from the pkg directory and the <code>publish</code> command creates a tarball from the
pkg directory <strong>and</strong> publishes it to the NPM registry.</p>
<p>Underneath, these commands use <code>npm pack</code> and <code>npm publish</code>. You can read
more about these in the NPM documentation:</p>
<ul>
<li><a href="https://docs.npmjs.com/cli/pack"><code>npm pack</code></a></li>
<li><a href="https://docs.npmjs.com/cli/publish"><code>npm publish</code></a></li>
</ul>
<p>Both these commands take the path to the pkg directory as the first argument.
You can either set the argument directly to the pkg directory or to the parent
of the pkg directory:</p>
<pre><code>$ wasm-pack pack myproject/pkg
| 🎒  packed up your package!
$ wasm-pack pack myproject
| 🎒  packed up your package!
</code></pre>
<p>If you try to call <code>pack</code> or <code>publish</code> on another directory, you get an error:</p>
<pre><code>$ wasm-pack pack myproject/src/
Unable to find the pkg directory at path 'myproject/src/', or in a child directory of 'myproject/src/'
</code></pre>
<p>If you don't set a path, they use the current directory as the path.</p>
<a class="header" href="#publishing-tagged-releases" id="publishing-tagged-releases"><h2>Publishing tagged releases</h2></a>
<p>You can also publish tagged releases with the optional <code>--tag</code> argument, e.g.</p>
<pre><code>wasm-pack publish --tag next
</code></pre>
<p>By default, the <code>latest</code> tag is used to identify the current version of a package,
and npm install &lt;pkg&gt; (without any @&lt;version&gt; or @&lt;tag&gt; specifier) installs the latest tag.</p>
<p>You can read more about <a href="https://docs.npmjs.com/cli/dist-tag">distribution tags</a> on NPM.</p>
<a class="header" href="#wasm-pack-init-deprecated" id="wasm-pack-init-deprecated"><h1>wasm-pack init (DEPRECATED)</h1></a>
<p>This command has been deprecated in favor of <code>build</code>, which does the same thing, but is
a much more representative name for the command. <a href="./build.html">Read the docs for <code>build</code>.</a></p>
<a class="header" href="#tutorials" id="tutorials"><h1>Tutorials</h1></a>
<p>We have two tutorials that help you get started with <code>wasm-pack</code>:</p>
<ul>
<li>If you want to create and publish a package: <a href="npm-browser-packages/index.html">npm browser packages</a></li>
<li>If you'd like to develop a Wasm library alongside a JavaScript application using Webpack: <a href="hybrid-applications-with-webpack/index.html">Hybrid applications with Webpack</a></li>
</ul>
<a class="header" href="#hybrid-applications-with-webpack" id="hybrid-applications-with-webpack"><h1>Hybrid Applications with Webpack</h1></a>
<p>The goal of this tutorial is to introduce you to the <a href="https://github.com/rustwasm/rust-webpack-template"><code>rust-webpack-template</code></a>
and the <code>wasm-pack</code> workflow by building the example app in the template.</p>
<p>This tutorial is aimed at folks who are both beginners to WebAssembly and Rust- you don't need
much Rust knowledge to complete this tutorial.</p>
<p>Be sure to have read and followed the <a href="../../prerequisites/index.html">Prerequisites</a>.</p>
<a class="header" href="#getting-started" id="getting-started"><h1>Getting Started</h1></a>
<p>You can create a new Rust-WebAssembly webpack project by using the <a href="https://github.com/rustwasm/rust-webpack-template">rustwasm webpack-template</a>.</p>
<p>Run:</p>
<pre><code>npm init rust-webpack my-app
</code></pre>
<p>The last argument will be your project name. After you run the command, you will have a
directory with a new project, ready to go. We'll talk about what's been included in this
template further in this guide.</p>
<a class="header" href="#run-the-code" id="run-the-code"><h1>Run The Code</h1></a>
<p>The Rust Webpack template is designed for creating monorepo-style Web applications with
Rust-generated WebAssembly and Webpack without publishing your wasm to NPM.
This portion of the tutorial will explain how to build a <a href="https://webpack.js.org/">Webpack</a> JavaScript project
that will run your WebAssembly code in the browser.</p>
<a class="header" href="#scaffold-a-javascript-project" id="scaffold-a-javascript-project"><h2>Scaffold a JavaScript Project</h2></a>
<p>To generate a new Rust Webpack project, we've used the <a href="https://github.com/rustwasm/rust-webpack-template"><code>rust-webpack</code></a> npm template.</p>
<pre><code>npm init rust-webpack your-package-name
</code></pre>
<p>A new project folder will be created with the name you supply.</p>
<p>If we look in the project, we'll see the following:</p>
<ul>
<li><code>.gitignore</code>: ignores <code>node_modules</code></li>
<li><code>LICENSE-APACHE</code> and <code>LICENSE-MIT</code>: most Rust projects are licensed this way, so these are included for you</li>
<li><code>README.md</code>: the file you are reading now!</li>
<li><code>index.html</code>: a bare bones html document that includes the webpack bundle</li>
<li><code>js/index.js</code>: example JS file with a comment showing how to import and use a wasm pkg</li>
<li><code>package.json</code> and <code>package-lock.json</code>:
<ul>
<li>pulls in devDependencies for using webpack:
<ul>
<li><a href="https://www.npmjs.com/package/webpack"><code>webpack</code></a></li>
<li><a href="https://www.npmjs.com/package/webpack-cli"><code>webpack-cli</code></a></li>
<li><a href="https://www.npmjs.com/package/webpack-dev-server"><code>webpack-dev-server</code></a></li>
</ul>
</li>
<li>defines a <code>start</code> script to run <code>webpack-dev-server</code></li>
</ul>
</li>
<li><code>webpack.config.js</code>: configuration file for bundling your JS with webpack</li>
<li><code>crate/src/lib.rs</code>: your Rust crate code!</li>
</ul>
<a class="header" href="#your-rust-crate" id="your-rust-crate"><h2>Your Rust Crate</h2></a>
<p>The scaffolded project includes an example Rust WebAssembly webpack crate.</p>
<p>Inside the <code>crate/src/lib.rs</code> file we see a <code>run</code> function that's callable from our JS file:</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
// Called by our JS entry point to run the example.
#[wasm_bindgen]
pub fn run() -&gt; Result&lt;(), JsValue&gt; {
    set_panic_hook();

    // ...
    let p: web_sys::Node = document.create_element(&quot;p&quot;)?.into();
    p.set_text_content(Some(&quot;Hello from Rust, WebAssembly, and Webpack!&quot;));
    // ...

    Ok(())
}
#}</code></pre></pre>
<p>Now, open up the <code>js/index.js</code> file. We see our Rust-generated wasm <code>run</code> function being
called inside our JS file.</p>
<pre><code class="language-js">import(&quot;../crate/pkg&quot;).then(module =&gt; {
  module.run();
});
</code></pre>
<a class="header" href="#run-the-project" id="run-the-project"><h2>Run The Project</h2></a>
<p>To generate our Rust-compiled to wasm code, in the root directory we run:</p>
<pre><code class="language-bash">npm run build
</code></pre>
<p>This will create our bundled JavaScript module in a new directory <code>dist</code>.</p>
<p>We should be ready to run our project now!
In the root directory, we'll run:</p>
<pre><code class="language-bash">npm start
</code></pre>
<p>Then in a web browser navigate to <code>http://localhost:8080</code> and you should be greeted
with text in the body of the page that says &quot;Hello from Rust, WebAssembly, and Webpack!&quot;</p>
<p>If you did congrats! You've successfully used the rust-webpack template!</p>
<a class="header" href="#npm-browser-package-tutorial" id="npm-browser-package-tutorial"><h1>npm Browser Package Tutorial</h1></a>
<p>The goal of this tutorial is to introduce you to the <code>wasm-pack</code> workflow by building a small npm
package designed to be used in a browser application.</p>
<p>This tutorial is aimed at folks who are both beginners to WebAssembly and Rust- you don't need
much Rust knowledge to complete this tutorial.</p>
<p>Be sure to have done the following before starting:</p>
<ol>
<li><a href="https://rustwasm.github.io/wasm-pack/installer/">Install <code>wasm-pack</code></a></li>
<li>Read and install the <a href="../../prerequisites/index.html">Prerequisites</a>.</li>
</ol>
<p>⚠️ We strongly recommend that you install <a href="https://nodejs.org">Node.js</a> using a version manager. You can learn more <a href="https://npmjs.com/get-npm">here</a>.</p>
<a class="header" href="#getting-started-1" id="getting-started-1"><h1>Getting Started</h1></a>
<p>You can create a new Rust-WebAssembly project by using the <a href="https://github.com/rustwasm/wasm-pack-template">rustwasm wasm-pack-template</a>.</p>
<p>To so do, you'll need the <code>cargo-generate</code> tool. To install <code>cargo-generate</code>:</p>
<pre><code>cargo install cargo-generate
</code></pre>
<p>Then run:</p>
<pre><code>cargo generate --git https://github.com/rustwasm/wasm-pack-template
</code></pre>
<p>You will be prompted to give your project a name. Once you do, you will have a directory
with a new project, ready to go. We'll talk about what's been included in this template
further in this guide.</p>
<a class="header" href="#manual-setup" id="manual-setup"><h2>Manual Setup</h2></a>
<p>⚠️ If you'd rather not use a template, or are having trouble with the template, you can
do a manual setup by following <a href="./getting-started/manual-setup.html">these instructions</a>.</p>
<a class="header" href="#manual-setup-1" id="manual-setup-1"><h1>Manual Setup</h1></a>
<p>⚠️ This is not the recommended way to start a <code>wasm-pack</code> project! If you ended up
here by mistake, go check out our <a href="../getting-started.html">recommended project start</a>.</p>
<a class="header" href="#step-1-create-a-new-rust-library-project" id="step-1-create-a-new-rust-library-project"><h3>Step 1: Create a New Rust Library Project</h3></a>
<p>You can create a new Rust project named <code>my-lib</code> using this command.</p>
<pre><code>cargo new --lib my-lib
</code></pre>
<p>The <code>--lib</code> flag specifies that the project is a library, which is important
because we will be calling this code from JavaScript.</p>
<a class="header" href="#step-2-edit-your-cargotoml-file" id="step-2-edit-your-cargotoml-file"><h3>Step 2: Edit your <code>Cargo.toml</code> File</h3></a>
<a class="header" href="#add-the-wasm-bindgen-dependency" id="add-the-wasm-bindgen-dependency"><h4>Add the <code>wasm-bindgen</code> dependency</h4></a>
<p>You will need to add <code>wasm-bindgen</code> to your <code>Cargo.toml</code> in the dependencies
section. <code>wasm-bindgen</code> is a tool that facilitates interoperability between
wasm modules and JavaScript.</p>
<p>⚠️ If you are coming from JavaScript, you might note that when we add the dependency
there is no <code>^</code> or <code>~</code> symbol- it looks like we're locking to the <code>0.2</code> version.
However, that's not the case! In Rust, the <code>^</code> is implied.</p>
<a class="header" href="#add-crate-type" id="add-crate-type"><h4>Add <code>crate-type</code></h4></a>
<p>Next, add a <code>[lib]</code> section, with a new field named <code>crate-type</code> set to
<code>&quot;cdylib&quot;</code>. This specifies that the library is a C compatible dynamic library,
which helps <code>cargo</code> pass the correct flags to the Rust compiler when targeting
<code>wasm32</code>.</p>
<p>After making these changes, your <code>Cargo.toml</code> file should look something like
this:</p>
<pre><code class="language-toml">[package]
name = &quot;hello-wasm&quot;
version = &quot;0.1.0&quot;
authors = [&quot;Ashley Williams &lt;ashley666ashley@gmail.com&gt;&quot;]
description = &quot;babby's first wasm package&quot;
license = &quot;MIT OR Apache-2.0&quot;
repository = &quot;https://github.com/ashleygwilliams/hello-wasm&quot;

[lib]
crate-type = [&quot;cdylib&quot;]

[dependencies]
wasm-bindgen=&quot;0.2&quot;
</code></pre>
<a class="header" href="#step-3-write-some-rust" id="step-3-write-some-rust"><h3>Step 3: Write some Rust!</h3></a>
<p>Now that your crate is correctly configured in your <code>Cargo.toml</code> file, the only step
left to setup your project is to have some Rust code in your <code>src/lib.rs</code> file.</p>
<a class="header" href="#browser-example" id="browser-example"><h4>Browser Example</h4></a>
<p>The template we have gives you a quick &quot;Hello, World&quot; project to use for compiling into
a WebAssembly library that you can use in the browser:</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
extern crate wasm_bindgen;

use wasm_bindgen::prelude::*;

#[wasm_bindgen]
extern {
    fn alert(s: &amp;str);
}

#[wasm_bindgen]
pub fn greet() {
    alert(&quot;Hello, World!&quot;);
}
#}</code></pre></pre>
<p>And that's it! We'll talk about what this code does in the <a href="../template-deep-dive/index.html">template deep dive</a>, which you are all
setup for now. Happy <code>wasm-pack</code>ing!</p>
<a class="header" href="#template-deep-dive" id="template-deep-dive"><h1>Template Deep Dive</h1></a>
<p>⚠️ This section is a deep dive into the contents of the files of a &quot;Hello, World&quot; project,
specifically written for people who are not that familiar with Rust. If you'd rather just
checkout the workflow, feel free to skip this section!</p>
<p>⚠️ If you haven't used a template to set up your project, the contents of your files
may look slightly different than what is described here.</p>
<a class="header" href="#what-the-template-gave-us" id="what-the-template-gave-us"><h3>What the Template Gave Us</h3></a>
<p>Let's start by taking a look at what the template generated for us.</p>
<ul>
<li><a href="./cargo-toml.html"><code>Cargo.toml</code> - the Cargo manifest</a></li>
<li><a href="./src-lib-rs.html"><code>src/lib.rs</code> - main library module</a></li>
<li><a href="./src-utils-rs.html"><code>src/utils.rs</code> - a utility module</a></li>
<li><a href="./wee_alloc.html"><code>wee_alloc</code> - a tiny memory allocator</a></li>
<li><a href="./tests-web-rs.html"><code>tests/web.rs</code> - running headless browser tests</a></li>
</ul>
<a class="header" href="#cargotoml" id="cargotoml"><h1>Cargo.toml</h1></a>
<p><code>Cargo.toml</code> is the manifest file for Rust's package manager, <a href="https://doc.rust-lang.org/cargo/"><code>cargo</code></a>. This file contains
metadata such as name, version, and dependencies for packages, which are call &quot;crates&quot; in Rust.</p>
<p>There's a bunch of metadata that the template gives us, but there are three key parts to discuss:</p>
<ol>
<li><a href="#a1-crate-type"><code>crate-type</code></a></li>
<li><a href="#a2-wasm-bindgen-dependency"><code>wasm-bindgen</code> dependency</a></li>
<li><a href="#a3-features-and-wee_alloc-console_error_panic_hook-dependencies"><code>[features]</code> and <code>wee_alloc</code>, <code>console_error_panic_hook</code> dependencies</a></li>
</ol>
<hr/>
<a class="header" href="#1-crate-type" id="1-crate-type"><h2>1. <code>crate-type</code></h2></a>
<pre><code class="language-toml">[lib]
crate-type = [&quot;cdylib&quot;, &quot;rlib&quot;]
</code></pre>
<p>A Rust-<code>wasm</code> crate is a bit different from a normal crate, and as a result, we need to note
this in our <code>Cargo.toml</code>.</p>
<p>This <code>[lib]</code> annotation is typically not needed in Cargo projects, and if you're
familiar with other Rust crates you'll remember that the most common crate types
are <code>rlib</code> (the default) or <code>bin</code> for binaries (which don't need a <code>crate-type</code>
annotation).</p>
<p>Here though <code>crate-type = [&quot;cdylib&quot;]</code> typically signifies that you'd like the
compiler to create a dynamic system library, but for WebAssembly target it
simply means &quot;create a <code>*.wasm</code> file without a <code>start</code> function&quot;. On other
platforms this output type will create <code>*.so</code> file on Linux, <code>*.dylib</code> on
macOS, and <code>*.dll</code> Windows.</p>
<p>We also specify <code>crate-type = [&quot;rlib&quot;]</code> to ensure that our library can be unit
tested with <code>wasm-pack test</code> (which we'll see later). Without this we wouldn't
be able to test our library because the <code>cdylib</code> crate type is incompatible with
<code>wasm-pack</code>'s style of unit tests.</p>
<p>You can read more about linking and crate types, <a href="https://doc.rust-lang.org/reference/linkage.html">here</a>.</p>
<a class="header" href="#2-wasm-bindgen-dependency" id="2-wasm-bindgen-dependency"><h2>2. <code>wasm-bindgen</code> dependency</h2></a>
<p><a href="https://rustwasm.github.io/docs/wasm-bindgen/"><code>wasm-bindgen</code></a> is our most important dependency. This package allows us to use the
<code>#[wasm-bindgen]</code> attribute to tag code that represents the interface we want between
our JavaScript and Rust-generated <code>wasm</code>. We can import JS and export Rust by using this
attribute.</p>
<pre><code class="language-toml">wasm-bindgen = &quot;0.2&quot;
</code></pre>
<p>We'll see more about how to use this library when we discuss what has been generated in <code>lib.rs</code>.</p>
<p>⚠️ If you are coming from JavaScript, you might note that when we add the dependency
there is no <code>^</code> or <code>~</code> symbol- it looks like we're locking to the <code>0.2</code> version.
However, that's not the case! In Rust, the <code>^</code> is implied. You can read more about this in the
<a href="https://doc.rust-lang.org/cargo/reference/specifying-dependencies.html">cargo documentation on specifying dependencies</a>.</p>
<a class="header" href="#3-features-and-a-hrefhttpscratesiocrateswee_allocwee_alloca-a-hrefhttpscratesiocratesconsole_error_panic_hookconsole_error_panic_hooka-dependencies" id="3-features-and-a-hrefhttpscratesiocrateswee_allocwee_alloca-a-hrefhttpscratesiocratesconsole_error_panic_hookconsole_error_panic_hooka-dependencies"><h2>3. <code>[features]</code> and <a href="https://crates.io/crates/wee_alloc"><code>wee_alloc</code></a>, <a href="https://crates.io/crates/console_error_panic_hook"><code>console_error_panic_hook</code></a> dependencies</h2></a>
<p>As part of our effort to design a template that helps people discover useful crates
for their particular use case, this template includes two dependencies that can be
very useful for folks developing Rust-<code>wasm</code> crates:<a href="https://crates.io/crates/console_error_panic_hook"> <code>console_error_panic_hook</code></a> and
<a href="https://crates.io/crates/wee_alloc"><code>wee_alloc</code></a>.</p>
<p>Because these dependencies are useful primarily in a specific portion of the Rust-<code>wasm</code>
crate development workflow, we've also set up a bit of glue code that allows us to include
them both as dependencies, but also allows them to be optionally included.</p>
<pre><code class="language-toml">[features]
default = [&quot;console_error_panic_hook&quot;]

[dependencies]
wasm-bindgen = &quot;0.2&quot;

# The `console_error_panic_hook` crate provides better debugging of panics by
# logging them with `console.error`. This is great for development, but requires
# all the `std::fmt` and `std::panicking` infrastructure, so isn't great for
# code size when deploying.
console_error_panic_hook = { version = &quot;0.1.1&quot;, optional = true }

# `wee_alloc` is a tiny allocator for wasm that is only ~1K in code size
# compared to the default allocator's ~10K. It is slower than the default
# allocator, however.
#
# Unfortunately, `wee_alloc` requires nightly Rust when targeting wasm for now.
wee_alloc = { version = &quot;0.4.2&quot;, optional = true }
</code></pre>
<p>In our code, we'll mark certain parts of code as running only if certain <code>[features]</code>
are enabled, specifically, <code>console_error_panic_hook</code> and <code>wee_alloc</code>. By default,
only <code>console_error_panic_hook</code> is enabled. To disable or enable either feature, by
default, we can edit the <code>default</code> vector under <code>[features]</code>.</p>
<p>To learn more about these features, we discuss them in-depth in the <a href="src-lib-rs.html"><code>src/lib.rs</code></a> and
<a href="src-utils-rs.html"><code>src/utils.rs</code></a> sections.</p>
<p>Briefly, they include:</p>
<ul>
<li><strong>console_error_panic_hook</strong> for logging panic messages to the developer console.</li>
<li><strong>wee_alloc</strong>, an allocator optimized for small code size.</li>
</ul>
<a class="header" href="#srclibrs" id="srclibrs"><h1>src/lib.rs</h1></a>
<p><code>lib.rs</code> is the template's main source file. The name <code>lib.rs</code> commonly implies that this Rust project will be compiled as a library.</p>
<p>It contains three key parts:</p>
<ol>
<li><a href="#a1-wasm_bindgen-functions"><code>#[wasm_bindgen] functions</code></a></li>
<li><a href="#a2-crate-imports">Crate imports</a></li>
<li><a href="#a3-wee_alloc-optional-dependecy"><code>wee_alloc</code> optional dependecy</a>
<ul>
<li><a href="#what-is-wee_alloc">What is <code>wee_alloc</code>?</a></li>
</ul>
</li>
</ol>
<hr />
<p>We'll start with the most important part of <code>lib.rs</code> -- the two <code>#[wasm_bindgen]</code> functions (which you can find at the bottom of the file). In many cases, this is the only part of <code>lib.rs</code> you will need to modify.</p>
<a class="header" href="#1-using-wasm_bindgen" id="1-using-wasm_bindgen"><h2>1. Using <code>wasm_bindgen</code></h2></a>
<p>To expose functionality from the <code>wasm-bindgen</code> crate more conveniently we can use the <code>use</code> keyword.
<code>use</code> allows us to conveniently refer to parts of a crate or module. You can learn more about how Rust
lets you write modular code in <a href="https://doc.rust-lang.org/book/ch07-02-modules-and-use-to-control-scope-and-privacy.html">this chapter of the book</a>.</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
use wasm_bindgen::prelude::*;
#}</code></pre></pre>
<p>Many crates contain a prelude, a list of things that are convenient to import
all at once. This allows common features of the module to be conveniently
accessed without a lengthy prefix. For example, in this file we can use
<code>#[wasm_bindgen]</code> only because it is brought into scope by the prelude.</p>
<p>The asterisk at the end of this <code>use</code> indicates that everything inside the module <code>wasm_bindgen::prelude</code> (i.e. the module <code>prelude</code> inside the crate <code>wasm_bindgen</code>) can be referred to without prefixing it with <code>wasm_bindgen::prelude</code>.</p>
<p>For example, <code>#[wasm_bindgen]</code> could also be written as <code>#[wasm_bindgen::prelude::wasm_bindgen]</code>, although this is not recommended.</p>
<a class="header" href="#1-wasm_bindgen-functions" id="1-wasm_bindgen-functions"><h2>1. <code>#[wasm_bindgen]</code> functions</h2></a>
<p>The <code>#[wasm_bindgen]</code> attribute indicates that the function below it will be accessible both in JavaScript and Rust.</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
#[wasm_bindgen]
extern {
    fn alert(s: &amp;str);
}
#}</code></pre></pre>
<p>The <code>extern</code> block imports the external JavaScript function <code>alert</code> into Rust. This declaration is required to call <code>alert</code> from Rust. By declaring it in this way, <code>wasm-bindgen</code> will create JavaScript stubs for <code>alert</code> which allow us to pass strings back and forth between Rust and JavaScript.</p>
<p>We can see that the <code>alert</code> function requires a single parameter <code>s</code> of type <code>&amp;str</code>, a string. In Rust, any string literal such as <code>&quot;Hello, test-wasm!&quot;</code> is of type <code>&amp;str</code>. So, <code>alert</code> could be called by writing <code>alert(&quot;Hello, test-wasm!&quot;);</code>.</p>
<p>We knew to declare <code>alert</code> in this way because it is how we would call <code>alert</code> in JavaScript -- by passing it a string argument.</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
#[wasm_bindgen]
pub fn greet() {
    alert(&quot;Hello, test-wasm!&quot;);
}
#}</code></pre></pre>
<p>If we were to write the <code>greet</code> function without the <code>#[wasm_bindgen]</code> attribute, then <code>greet</code> would not be easily accessible within JavaScript. Furthermore, we wouldn't be able to natively convert certain types such as <code>&amp;str</code> between JavaScript and Rust. So, both the <code>#[wasm_bindgen]</code> attribute and the prior import of <code>alert</code> allow <code>greet</code> to be called from JavaScript.</p>
<p>This is all you need to know to interface with JavaScript, at least to start! You can learn a bunch more by reading the
<a href="https://rustwasm.github.io/docs/wasm-bindgen/"><code>wasm-bindgen</code> documentation</a>!</p>
<p>If you are curious about the rest, read on.</p>
<a class="header" href="#2-crate-organization" id="2-crate-organization"><h2>2. Crate Organization</h2></a>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
mod utils;
#}</code></pre></pre>
<p>This statement declares a new module named <code>utils</code> that is defined by the contents of <code>utils.rs</code>. Equivalently, we could place the contents of <code>utils.rs</code> inside the <code>utils</code> declaration, replacing the line with:</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
mod utils {
    // contents of utils.rs
}
#}</code></pre></pre>
<p>Either way, the contents of <code>utils.rs</code> define a single public function <code>set_panic_hook</code>. Because we are placing it inside the <code>utils</code> module, we will be able to call the function directly by writing <code>utils::set_panic_hook()</code>. We will discuss how and why to use this function in <code>src/utils.rs</code>.</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
    // When the `wee_alloc` feature is enabled, use `wee_alloc` as the global
    // allocator.
    if #[cfg(feature = &quot;wee_alloc&quot;)] {
        #[global_allocator]	static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT;
#}</code></pre></pre>
<p>At compile time this will test if the <code>wee_alloc</code> feature is enabled for this
compilation. If it's enabled we'll configure a global allocator (according to
<a href="https://docs.rs/wee_alloc/0.4.3/wee_alloc/"><code>wee_alloc</code>'s docs</a>), otherwise it'll compile to nothing.</p>
<p>As we saw earlier, the <code>default</code> vector in <code>[features]</code> only contains <code>&quot;console_error_panic_hook&quot;</code> and not <code>&quot;wee_alloc&quot;</code>. So, in this case, this
block will be replaced by no code at all, and hence the default memory allocator will be used instead of <code>wee_alloc</code>.</p>
<a class="header" href="#srcutilsrs" id="srcutilsrs"><h1>src/utils.rs</h1></a>
<p>The purpose of <code>utils.rs</code> is to define the <code>utils</code> module, which contains a single function <code>set_panic_hook</code>. This function becomes part of the <code>utils</code> module in <code>lib.rs</code>, as described in the preceding section.</p>
<p>If the <code>console_error_panic_hook</code> feature is not enabled, then <code>set_panic_hook</code> is defined to be an inlined empty function. So, there is no run-time performance or code-size penalty incurred by its use.</p>
<p>We will discuss:</p>
<ol>
<li><a href="#1-defining-set_panic_hook">Defining <code>set_panic_hook</code></a></li>
<li><a href="#2-what-is-console_error_panic_hook">What is <code>console_error_panic_hook</code>?</a></li>
</ol>
<hr />
<a class="header" href="#1-defining-set_panic_hook" id="1-defining-set_panic_hook"><h2>1. Defining <code>set_panic_hook</code></h2></a>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
pub fn set_panic_hook() {
    // When the `console_error_panic_hook` feature is enabled, we can call the
    // `set_panic_hook` function at least once during initialization, and then
    // we will get better error messages if our code ever panics.
    //
    // For more details see
    // https://github.com/rustwasm/console_error_panic_hook#readme
    #[cfg(feature = &quot;console_error_panic_hook&quot;)]
    console_error_panic_hook::set_once();
}
#}</code></pre></pre>
<p>Here, we define a function that's preceded by a <code>cfg</code> attribute. This attribue,
<code>#[cfg(feature = &quot;console_error_panic_hook&quot;)]</code>, tells Rust to check if the
<code>console_error_panic_hook</code> feature is set at compile time. If it is, it will call
this function. If it isn't- it won't!</p>
<a class="header" href="#2-what-is-console_error_panic_hook" id="2-what-is-console_error_panic_hook"><h2>2. What is <code>console_error_panic_hook</code>?</h2></a>
<p>The <a href="https://crates.io/crates/console_error_panic_hook">crate <code>console_error_panic_hook</code></a> allows debugging Rust panic
messages in a web browser, making it much easier to debug WebAssembly code.</p>
<p>Let's compare what happens when Rust code panics before and after enabling the
feature:</p>
<p><strong>Before:</strong> <code>&quot;RuntimeError: Unreachable executed&quot;</code></p>
<p><strong>After:</strong> <code>&quot;panicked at 'index out of bounds: the len is 3 but the index is 4', libcore/slice/mod.rs:2046:10&quot;</code></p>
<p>To do this, a <a href="https://doc.rust-lang.org/std/panic/fn.set_hook.html">panic hook</a> is configured that logs panics to the
developer console via the JavaScript <code>console.error</code> function.</p>
<p>Note though that <code>console_error_panic_hook</code> is not entirely automatic, so you'll
need to make sure that <code>utils::set_panic_hook()</code> is called before any of our
code runs (and it's safe to run <code>set_panic_hook</code> many times).</p>
<p>For more details, see the <a href="https://github.com/rustwasm/console_error_panic_hook"><code>console_error_panic_hook</code>
repository</a>.</p>
<a class="header" href="#wee_alloc" id="wee_alloc"><h1>wee_alloc</h1></a>
<ol>
<li><a href="#what-is-wee_alloc">What is <code>wee_alloc</code>?</a></li>
<li><a href="#enabling-wee_alloc">Enabling <code>wee_alloc</code></a></li>
</ol>
<a class="header" href="#what-is-wee_alloc" id="what-is-wee_alloc"><h2>What is <code>wee_alloc</code>?</h2></a>
<p>WebAssembly code is frequently transmitted over the wire to users, so compiled
code size is often important to ensure an application loads quickly and is
responsive.</p>
<blockquote>
<p><code>wee_alloc</code> is a tiny allocator designed for WebAssembly that has a (pre-compression) code-size footprint of only a single kilobyte.</p>
</blockquote>
<p><a href="http://fitzgeraldnick.com/2018/02/09/wee-alloc.html">An analysis</a> suggests that over half of the bare minimum WebAssembly memory footprint is required by Rust's default memory allocator. Yet, WebAssembly code often does not require a sophisticated allocator, since it often just requests a couple of large initial allocations.</p>
<p><code>wee_alloc</code> trades off size for speed. It has a tiny code-size
footprint, but it is not competitive in terms of performance with the
default global allocator, for example.</p>
<p>For even more details, see the <a href="https://github.com/rustwasm/wee_alloc"><code>wee_alloc</code>
repository</a>, or
<a href="https://rustwasm.github.io/docs/book/reference/code-size.html">general documentation</a> about
shrinking code size of WebAssembly binaries.</p>
<a class="header" href="#enabling-wee_alloc" id="enabling-wee_alloc"><h2>Enabling <code>wee_alloc</code></h2></a>
<p>In <code>lib.rs</code>, we have the configuration for <code>wee_alloc</code> inside a <code>cfg_if!</code> macro:</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
cfg_if! {
    if #[cfg(feature = &quot;wee_alloc&quot;)] {
        #[global_allocator]
        static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT;
    }
}
#}</code></pre></pre>
<p>This code block is intended to initialize <code>wee_alloc</code> as the global memory
allocator, but only if the <code>wee_alloc</code> feature is enabled at compile time. The
feature can be enabled by passing extra options while building:</p>
<pre><code>$ wasm-pack build --features wee_alloc
</code></pre>
<p>or alternatively you could turn it on by default in <code>Cargo.toml</code>:</p>
<pre><code class="language-toml">[features]
default = [&quot;console_error_panic_hook&quot;, &quot;wee_alloc&quot;]
</code></pre>
<a class="header" href="#testswebrs" id="testswebrs"><h1>tests/web.rs</h1></a>
<p><code>web.rs</code> is an integration test <a href="https://doc.rust-lang.org/cargo/guide/tests.html">defined with Cargo</a> that is
intended to be run in a headless web browser via the <code>wasm-pack test</code> command.</p>
<p>It contains three key parts:</p>
<ol>
<li><a href="#a1-wasm_bindgen_test-functions"><code>#[wasm_bindgen_test] functions</code></a></li>
<li><a href="#a2-crate-configuration">Crate Configuration</a></li>
<li><a href="#a3-cfg-directives"><code>#![cfg]</code> directives</a></li>
</ol>
<hr />
<a class="header" href="#1-wasm_bindgen_test-functions" id="1-wasm_bindgen_test-functions"><h2>1. <code>#[wasm_bindgen_test]</code> functions</h2></a>
<p>The <code>#[wasm_bindgen_test]</code> is like the <a href="https://doc.rust-lang.org/book/ch11-01-writing-tests.html">normal Rust <code>#[test]</code>
attribute</a>, except it defines a test accessible to WebAssembly and
headless web browser testing.</p>
<blockquote>
<p><strong>Note</strong>: Eventually <code>#[test]</code> will work with WebAssembly as well! Currently
though <a href="https://github.com/rust-lang/rust/issues/50297">custom test frameworks</a> are not stable.</p>
</blockquote>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
#[wasm_bindgen_test]
fn pass() {
    assert_eq!(1 + 1, 2);
}
#}</code></pre></pre>
<p>Here the <code>pass</code> function is a unit test which asserts that arithmetic works in
WebAssembly like we'd expect everywhere else. If the test panics (such as the
<code>assert_eq!</code> being false) then the test will fail, otherwise the test will
succeed.</p>
<p>The <a href="https://rustwasm.github.io/docs/wasm-bindgen/wasm-bindgen-test/index.html">reference documentation for <code>#[wasm_bindgen_test]</code></a> should have
more information about defining these tests.</p>
<a class="header" href="#2-crate-configuration" id="2-crate-configuration"><h2>2. Crate Configuration</h2></a>
<p>Other than the test in this module, we'll also see:</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
use wasm_bindgen_test::*;

wasm_bindgen_test_configure!(run_in_browser);
#}</code></pre></pre>
<p>Like we saw earlier in <code>src/lib.rs</code> the <code>*</code> import pulls in everything from
<code>wasm_bindgen_test</code>, notably the <code>wasm_bindgen_test_configure</code> macro and the
<code>wasm_bindgen_test</code> attribute.</p>
<p>The <code>wasm_bindgen_test_configure</code> macro (denoted by ending in <code>!</code>) is used to
indicate that the test is intended to execute in a web browser as opposed to
Node.js, which is the default.</p>
<a class="header" href="#3-cfg-directives" id="3-cfg-directives"><h2>3. <code>#![cfg]</code> directives</h2></a>
<p>The last part we'll notice about this crate is this statement at the top:</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#![cfg(target_arch = &quot;wasm32&quot;)]
#fn main() {
#}</code></pre></pre>
<p>This statement means that the test is only intended for the <code>wasm32</code>
architecture, or the <code>wasm32-unknown-unknown</code> target. This enables <code>cargo test</code>
to work in your project if the library is also being developed for other
platforms by ensuring that these tests only execute in a web browser.</p>
<a class="header" href="#building-your-project" id="building-your-project"><h1>Building your project</h1></a>
<p>We've written our code so now we need to build it.</p>
<p>We are writing a crate that should be used in the browser, so we run this in
our terminal:</p>
<pre><code class="language-bash">$ wasm-pack build
</code></pre>
<p>If you were writing a package that should be used in Node.js (with CommonJS
modules, e.g. <code>require</code>), you would run this in your terminal:</p>
<pre><code class="language-bash">$ wasm-pack build --target nodejs
</code></pre>
<p>This command when run does a few things:</p>
<ol>
<li>It'll compile your code to wasm if you haven't already</li>
<li>It'll generate a <code>pkg</code> folder with the wasm file, a JS wrapper file around
the wasm, your README, and a <code>package.json</code> file.</li>
</ol>
<a class="header" href="#testing-your-project" id="testing-your-project"><h1>Testing your project</h1></a>
<p>Now after writing and building code, let's actually execute it! You can execute
tests with:</p>
<pre><code class="language-bash">$ wasm-pack test --firefox
[INFO]: Checking for the Wasm target...
    Finished dev [unoptimized + debuginfo] target(s) in 0.02s
     Running target/wasm32-unknown-unknown/debug/deps/web-9e7d380f8600b08e.wasm
Interactive browsers tests are now available at http://127.0.0.1:8000

Note that interactive mode is enabled because `NO_HEADLESS`
is specified in the environment of this process. Once you're
done with testing you'll need to kill this server with
Ctrl-C.
</code></pre>
<p>The console won't finish just yet, but as indicated you can visit
http://127.0.0.1:8000 in your web browser to see the test output:</p>
<pre><code>running 1 test

test web::pass ... ok

test result: ok. 1 passed; 0 failed; 0 ignored
</code></pre>
<p>and we've now executed our first tests in a web browser!</p>
<p>If you'd like to execute tests in a headless web browser (you don't need to
manually visit a page) you can do:</p>
<pre><code class="language-bash">$ wasm-pack test --headless --firefox
</code></pre>
<p>and similarly if you're developing a project for Node.js you can also execute
<code>wasm-pack test --nodejs</code> to run tests in Node.</p>
<p>Be sure to see the <a href="https://rustwasm.github.io/docs/wasm-bindgen/wasm-bindgen-test/index.html">testing reference documentation</a> for
other supported features as well!</p>
<a class="header" href="#package-code-for-npm" id="package-code-for-npm"><h1>Package Code for npm</h1></a>
<p>We've made our code so now we need to package it all up. In your project directory run the following
command:</p>
<pre><code class="language-bash">$ wasm-pack build --scope MYSCOPE
</code></pre>
<p>where <code>MYSCOPE</code> is your npm username. Normally you could just type <code>wasm-pack build</code> but since
other people are doing this tutorial as well we don't want conflicts with the <code>wasm-add</code> package
name! This command when run does a few things:</p>
<ol>
<li>It'll compile your code to wasm if you haven't already</li>
<li>It'll generate a pkg folder with the wasm file, a JS wrapper file around the wasm, your README,
and a <code>package.json</code> file.</li>
</ol>
<p>This is everything you need to upload your code to npm! Let's do just that!</p>
<p>First off you'll need to login to npm with the account you made earlier if you didn't already have
one:</p>
<pre><code class="language-bash">$ wasm-pack login
</code></pre>
<p>Next you'll need to go into the <code>pkg</code> directory and actually upload the package:</p>
<pre><code class="language-bash">$ cd pkg
$ npm publish --access=public
</code></pre>
<p>Now normally if things are not scoped you can just do <code>npm publish</code> but if you give it a scope
you'll need to tell npm that this is actually public so it can publish it. We need to do that here
since we gave our packages a scope to avoid conflicting with each other! Next up is actually running
the code and verifying we got it from npm and how we can use that code.</p>
<a class="header" href="#run-the-code-from-npm" id="run-the-code-from-npm"><h1>Run The Code From npm</h1></a>
<p>This portion of the tutorial will help you create a <a href="https://webpack.js.org/">Webpack</a> JavaScript project that will
run your WebAssembly code in the browser.</p>
<a class="header" href="#scaffold-a-javascript-project-1" id="scaffold-a-javascript-project-1"><h2>Scaffold a JavaScript Project</h2></a>
<p>To scaffold a project that we can use our new package in, we'll use an npm template called
<a href="https://github.com/rustwasm/create-wasm-app"><code>create-wasm-app</code></a>. To use this run this command in a directory <em>different</em> than your Rust
project:</p>
<pre><code>npm init wasm-app my-new-wasm-app
</code></pre>
<p>Instead of <code>my-new-wasm-app</code> you can choose a different project name.
The tool will create a directory with that name.</p>
<p>If we look in that directory, we'll see the following:</p>
<ul>
<li><code>.gitignore</code>: ignores <code>node_modules</code></li>
<li><code>LICENSE-APACHE</code> and <code>LICENSE-MIT</code>: most Rust projects are licensed this way, so these are included for you</li>
<li><code>README.md</code>: the file you are reading now!</li>
<li><code>index.html</code>: a bare bones html document that includes the webpack bundle</li>
<li><code>index.js</code>: example js file with a comment showing how to import and use a wasm pkg</li>
<li><code>package.json</code> and <code>package-lock.json</code>:
<ul>
<li>pulls in devDependencies for using webpack:
<ul>
<li><a href="https://www.npmjs.com/package/webpack"><code>webpack</code></a></li>
<li><a href="https://www.npmjs.com/package/webpack-cli"><code>webpack-cli</code></a></li>
<li><a href="https://www.npmjs.com/package/webpack-dev-server"><code>webpack-dev-server</code></a></li>
</ul>
</li>
<li>defines a <code>start</code> script to run <code>webpack-dev-server</code></li>
</ul>
</li>
<li><code>webpack.config.js</code>: configuration file for bundling your js with webpack</li>
</ul>
<a class="header" href="#add-your-npm-package" id="add-your-npm-package"><h2>Add Your npm Package</h2></a>
<p>The scaffolded project includes an example WebAssembly package, <code>hello-wasm-pack</code>, in your
<code>package.json</code>. Go into the <code>package.json</code> file, add your package, and remove the
<code>hello-wasm-pack</code> dependency from the <code>&quot;dependencies&quot;</code> section.</p>
<p>Now, open up the <code>index.js</code> file. Replace the <code>hello-wasm-pack</code> in the first line with the
name of your package:</p>
<pre><code class="language-js">import * as wasm from &quot;&lt;your package name&gt;&quot;;

wasm.greet();
</code></pre>
<a class="header" href="#run-the-project-1" id="run-the-project-1"><h2>Run The Project</h2></a>
<p>Before we run our project, we need to make sure we install our dependencies:</p>
<pre><code class="language-bash">npm install
</code></pre>
<p>We should be ready to run our project now! To run our project we'll run:</p>
<pre><code class="language-bash">npm start
</code></pre>
<p>Then in a web browser navigate to <code>http://localhost:8080</code> and you should be greeted with an
alert box that says &quot;Hello World!&quot;.</p>
<p>If you did congrats you've successfully uploaded your first bit of wasm code to npm and used it
properly!</p>
<a class="header" href="#cargotoml-configuration" id="cargotoml-configuration"><h1><code>Cargo.toml</code> Configuration</h1></a>
<p><code>wasm-pack</code> can be configured via the <code>package.metadata.wasm-pack</code> key in
<code>Cargo.toml</code>. Every option has a default, and is not required.</p>
<p>There are three profiles: <code>dev</code>, <code>profiling</code>, and <code>release</code>. These correspond to
the <code>--dev</code>, <code>--profiling</code>, and <code>--release</code> flags passed to <code>wasm-pack build</code>.</p>
<p>The available configuration options and their default values are shown below:</p>
<pre><code class="language-toml">[package.metadata.wasm-pack.profile.dev]
# Should `wasm-opt` be used to further optimize the wasm binary generated after
# the Rust compiler has finished? Using `wasm-opt` can often further decrease
# binary size or do clever tricks that haven't made their way into LLVM yet.
#
# Configuration is set to `false` by default for the dev profile, but it can
# be set to an array of strings which are explicit arguments to pass to
# `wasm-opt`. For example `['-Os']` would optimize for size while `['-O4']`
# would execute very expensive optimizations passes
wasm-opt = ['-O']

[package.metadata.wasm-pack.profile.dev.wasm-bindgen]
# Should we enable wasm-bindgen's debug assertions in its generated JS glue?
debug-js-glue = true
# Should wasm-bindgen demangle the symbols in the &quot;name&quot; custom section?
demangle-name-section = true
# Should we emit the DWARF debug info custom sections?
dwarf-debug-info = false
# Should we omit the default import path?
omit-default-module-path = false

[package.metadata.wasm-pack.profile.profiling]
wasm-opt = ['-O']

[package.metadata.wasm-pack.profile.profiling.wasm-bindgen]
debug-js-glue = false
demangle-name-section = true
dwarf-debug-info = false
omit-default-module-path = false

# `wasm-opt` is on by default in for the release profile, but it can be
# disabled by setting it to `false`
[package.metadata.wasm-pack.profile.release]
wasm-opt = false

[package.metadata.wasm-pack.profile.release.wasm-bindgen]
debug-js-glue = false
demangle-name-section = true
dwarf-debug-info = false
omit-default-module-path = false
</code></pre>
<a class="header" href="#contributing" id="contributing"><h1>Contributing</h1></a>
<a class="header" href="#prerequisites-1" id="prerequisites-1"><h2>Prerequisites</h2></a>
<p>The technical prerequisites for contributing to this project are the same as for
using it. You can find them documented <a href="./prerequisites/index.html">here</a>.</p>
<p>You'll also want to check out the contributing <a href="https://github.com/rustwasm/wasm-pack/blob/master/CONTRIBUTING.md">guidelines</a>.</p>
<a class="header" href="#-up-and-running" id="-up-and-running"><h2>🏃‍♀️ Up and Running</h2></a>
<ol>
<li>fork and clone the <code>rustwasm/wasm-pack</code> repository</li>
<li>install [node/npm]</li>
<li><code>cd wasm-pack</code></li>
<li><code>cargo run</code>. To test command line arguments you can run <code>cargo run -- &lt;args&gt;</code>.</li>
</ol>
<a class="header" href="#documentation" id="documentation"><h2>Documentation</h2></a>
<p>Documentation lives in the <code>/docs</code> directory. Each command has its own page.
Additionally there are extra pages explaining the prerequisites, setup, and how to
contribute (which you are reading now!).</p>
<a class="header" href="#tests" id="tests"><h2>Tests</h2></a>
<p>Tests live in the <code>/tests</code> directory. To run the tests you can run:</p>
<pre><code>cargo test
</code></pre>
<p>You can also manually test the CLI tool by running:</p>
<pre><code>cargo run -- &lt;args&gt;
</code></pre>
<p>...for example:</p>
<pre><code>cargo run -- init /tests/fixtures/js-hello-world --scope=ag_dubs
</code></pre>

                    </main>

                    <nav class="nav-wrapper" aria-label="Page navigation">
                        <!-- Mobile navigation buttons -->
                        

                        

                        <div style="clear: both"></div>
                    </nav>
                </div>
            </div>

            <nav class="nav-wide-wrapper" aria-label="Page navigation">
                

                
            </nav>

        </div>

        

        

        

        

        <script src="clipboard.min.js" type="text/javascript" charset="utf-8"></script>
        <script src="highlight.js" type="text/javascript" charset="utf-8"></script>
        <script src="book.js" type="text/javascript" charset="utf-8"></script>

        <!-- Custom JS scripts -->
        

        
        
        <script type="text/javascript">
        window.addEventListener('load', function() {
            window.setTimeout(window.print, 100);
        });
        </script>
        
        

    </body>
</html>
